package com.atguigu.yygh.hosp;

import com.atguigu.yygh.hosp.mongoTest.User;
import com.atguigu.yygh.hosp.mongoTest.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.*;

import java.util.Date;
import java.util.List;

/**
 * @author:ahang
 * @create:2022-09-01 19:25
 * @Description:
 */
@SpringBootTest
public class MongoTest2 {

    @Autowired
    UserRepository userRepository;


    /**
     * 添加
     */
    @Test
    public void test1(){
        User user = new User();
        user.setName("tangtang");
        user.setAge(30);
        user.setCreateTime(new Date());

        User insert = userRepository.insert(user);
        System.out.println(insert);
    }

    /**
     * 修改
     */
    @Test
    public void test2(){
        User user = userRepository.findById("631097c1fdcf3d79e6d57eda").get();

        user.setAge(31);
        User save = userRepository.save(user);
        System.out.println(save);
    }

    /**
     * 模糊查询
     */
    @Test
    public void test3(){

        User user = new User();
        user.setName("t");

        ExampleMatcher matcher =
                ExampleMatcher
                        .matching()
                        .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//模糊查询
                        .withIgnoreCase(true); //忽略大小写

        Example<User> example = Example.of(user,matcher);
        List<User> all = userRepository.findAll(example);
        System.out.println(all);
    }

    /**
     * 分页查询
     */
    @Test
    public void test4(){
        PageRequest pageRequest = PageRequest.of(0, 2);
        Page<User> all = userRepository.findAll(pageRequest);

        System.out.println("总记录数"+all.getTotalElements());
        System.out.println("总页数"+all.getTotalPages());
        System.out.println("数据"+all.getContent());
    }

    /**
     * 排序
     */
    @Test
    public void test5(){
        Sort sort = Sort.by(Sort.Direction.ASC,"age");

        List<User> all = userRepository.findAll(sort);
        for (User user : all) {
            System.out.println(user);
        }
    }
}
